//
//  T3FJsonUtil.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/10/31.
//

import Foundation

struct T3FJsonUtil {

    static func toString(_ json: [String: Any]) throws -> String {

        let jsonData = try JSONSerialization.data(withJSONObject: json)
        // 将 Data 转换为字符串
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            return jsonString
        } else {
            throw T3FJsonUtilError.dataToStringError
        }
    }

    static func toJson(_ arguments: Any?) throws -> [String: Any] {
        if let jsonString = arguments as? String {
            if let data = jsonString.data(using: .utf8) {
                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options:[]) as? [String: Any] {
                        return json
                    }
                    else {
                        throw T3FJsonUtilError.invalidJson
                    }
                }
                catch(let error) {
                    throw error
                }
            }
            else {
                throw T3FJsonUtilError.dataToStringError
            }
        }
        else {
            throw T3FJsonUtilError.invalidString
        }
    }

    static func edgeInsetsFrom(json: [String: Double]) -> UIEdgeInsets? {

        guard let top = json["top"],
              let bottom = json["bottom"],
              let left = json["left"],
              let right = json["right"]
        else { return nil }

        return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
    }

    static func rectFrom(json: [String: Double]) -> CGRect? {

        guard let left = json["left"],
              let top = json["top"],
              let width = json["width"],
              let height = json["height"]
        else { return nil }

        return CGRect(x: left, y: top, width: width, height: height)
    }
}

private enum T3FJsonUtilError: Error {
    case dataToStringError
    case invalidJson
    case invalidString
}

extension T3FJsonUtilError: CustomStringConvertible {

    var description: String {
        switch self {
        case .dataToStringError:
            return "data转string错误"
        case .invalidJson:
            return "无效json"
        case .invalidString:
            return "无效string"
        }
    }
}





